import { message } from 'antd';
import $ from 'jquery';

import Reflux from 'reflux';
import RefluxPromise from 'reflux-promise';

import Q from 'q';
Reflux.use(RefluxPromise(Q.Promise));

//message全局配置
message.config({
  top: 100,
  duration: 2
});


const _ajax = $.ajax;

$.ajax = function(url, options,cbFn) { //  cbFn是回调
  // If url is an object, simulate pre-1.5 signature
  if ( typeof url === 'object' ) {
    options = url;
    url = undefined;
  }
  // Force options to be an object
  options = options || {};

  const _url = url || options.url;
  const _success = options.success;
  const _fail = options.fail;

  const genCallback = function(success, fail) {
    return function(data) {
      if (/notify|tenant/.test(_url)) {
        return success.apply(this, arguments);
      } else if (+data.errCode === 200) {
        return success.apply(this, arguments);
      } else if (+data.errCode === 401) {
        window.location.href = '/tenant/#/login?return_insite=' + encodeURIComponent(location.href);
      } else if (+data.errCode === 403) {
        //window.location.href = document.referrer;
        window.location.href = '/tenant/#/login?return_insite=' + encodeURIComponent(location.href);
      } else {
        //cbFn && cbFn();
        let code = "w" + data.errCode;
        if (cbFn) {
          var cb = cbFn();
          if (cb === "return_index") {
            fail.apply(this, arguments);
            window.location.href = "#/ticket/myToDo"
            return false;
          } else if (cb === "return_drafts") {
            return false;
          } else if (cb === 'return_flowChart') {
            return false;
          }
          message.error($.translate("server" , code));
        } else {
          message.error('776');
        }
        throw [log(_url),data.errCode, message.error("1")].join(': ');
      }
      return -1;
    }
  }

  if (_success || _fail) {
    options.success = genCallback(function() {
      _success.apply(this, arguments);
    },function() {
      _fail.apply(this, arguments);
    });
    return _ajax(url, options);
  } else {
    return _ajax(url, options).done(genCallback((data) => {
      return data;
    }))
  }
}

$(document).on('ajaxError', function(e, request) {
  switch (request.status) {
    case 401:
      window.location.href = '/tenant/#/login?return_insite=' + encodeURIComponent(location.href);
      break;
    default:
      //message.error('123');
      break;
  }
});

window.uy = {
  pageNum: 10,
  activityPageSize: 15
};
window.log = window.console.log;
